package org.redr.widgetGUI.settings;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CoreSettings extends XMLSetting{
	
	Document d;
	File settingsFile;
	
	public CoreSettings(File file) throws Exception{
		settingsFile = file;
		if (settingsFile.exists()){
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            d = docBuilder.parse (file);
            e = (Element) d.getElementsByTagName("Settings").item(0);
		} else {
			System.out.println("Settings file did not exist, creating a new default settings file in it's place.");
			System.out.println(settingsFile.toString());
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	 
			// root elements
			d = docBuilder.newDocument();
			
			e = d.createElement("Settings");
			d.appendChild(e);
		}
		setDefault("widgetListType", "3");
		setDefault("iconSize", "40");
		setDefault("toolbarIconSize", "1");
		setDefault("toolboxWidth", "200");
		setDefault("schemeIconSize", "2");
		setDefault("snapToGrid", "1");
		setDefault("helpMode", "true");
		setDefault("minSeverity", "5");
		setDefault("saveWidgetsPosition", "1");
		setDefault("widgetSelectedColor", "#00f000");
		setDefault("widgetActiveColor", "#0000ff");
		setDefault("lineColor", "#00ff00");

		setDefault("exceptionLevel", "5");
		// setdefault("WidgetTabs", []);

		//setdefault("workingDir", directoryNames['documentsDir']);
		//setdefault("saveSchemaDir", directoryNames['documentsDir']);
		//setdefault("saveApplicationDir", directoryNames['canvasSettingsDir']);
		setDefault("showSignalNames", "true");

		setDefault("canvasWidth", "900");
		setDefault("canvasHeight", "700");
		
		setDefault("notesDockState", "docked");
		setDefault("outputBox", "docked");
		setDefault("widgetBox", "docked");
		
		setDefault("useDefaultPalette", "0");

		setDefault("CRANrepos","http://cran.r-project.org");
		setDefault("keepForXDays", "7");

		/* 	############################
			#Updates##
			############################ */
		setDefault("lastUpdateCheckPackages", "0");
		setDefault("checkForPackageUpdates", "true");

		setDefault("checkForUpdates", "true");
		// setdefault("ignoredUpdates", []);

		setDefault("lastUpdateCheck", "0");
		setDefault("updateAvailable", "false");
		// setdefault("updatesRepository", "http://www.red-r.org/redr_updates/Red-R-" + version["REDRVERSION"]);

		/*
		############################
		#Dubug and output settings##
		############################
		*/
		
		setDefault("dontAskBeforeClose", "false");
		setDefault("askBeforeWidgetDelete", "true");

		setDefault("writeLogFile", "true");
		// setdefault("logsDir", directoryNames['logsDir']);
		setDefault("uploadError", "true");
		setDefault("askToUploadError", "false");

		setDefault("focusOnCatchException", "true");
		setDefault("focusOnCatchOutput" , "false");
		setDefault("printOutputInStatusBar", "false");
		setDefault("printExceptionInStatusBar", "false");
		setDefault("outputVerbosity", "3");
		setDefault("displayTraceback", "0");

		
		setDefault("ocShow", "1");
		setDefault("owShow", "0");
		setDefault("ocInfo", "1");
		setDefault("owInfo", "1");
		setDefault("ocWarning", "1");
		setDefault("owWarning", "1");
		setDefault("ocError", "1");
		setDefault("owError", "1");

		setDefault("synchronizeHelp", "1");
		setDefault("firstLoad", "true");
		setDefault("email", "");
		setDefault("canContact", "true");
		setDefault("REDRVERSION", "0.0.1");

		//setdefault('templateDirectories', [directoryNames['templatesDir']]);

		/*
		## language settings, these settings exist so that we can detect the language of the system
		settings.setdefault('language', OrderedDict([('en_EN.ISO8859-1', u'English'), ('fr_FR.ISO8859-1', u'Fran\u00E7aise'), ('de_DE.ISO8859-1', u'Deutsch'), ('latin', 'Latin')]))
		    """
		*/
		if (!settingsFile.getParentFile().exists()){
			System.out.println("Creating required core directories.");
			System.out.println("Creating directories returned: " + settingsFile.getParentFile().mkdirs());
					
		}
		
		if (!settingsFile.exists()){
			if (settingsFile.createNewFile()){
				saveSettings();
			} else {
				throw new Exception(String.format("Can't create the settings file \"%s\"!", settingsFile.toString()));
			}
		}
	}

	private void saveSettings() throws TransformerFactoryConfigurationError, TransformerException {
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");

		//initialize StreamResult with File object to save to file
		StreamResult result = new StreamResult(settingsFile);
		DOMSource source = new DOMSource(d);
		transformer.transform(source, result);
	}
	

}
